// pages/liji_goumai/liji_goumai.js
const app = getApp()
//获得全局js变量
var util = require('../../utils/util.js');
//加密算法
var crypto = require('../../utils/crypto-js.js'); 
//console.log(crypto.MD5('123456').toString());
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id:0,
        ggid:0,
        guige:'',
        phone:'',
        name:'',
        imgurl:app.data.imgurl,
        //信息
        userinfo: [],
        goodsinfo: [],
        //订单信息
        shuliang: 1,
        allmoney:0,//支付总价
        remark:'',//备注信息
        paytype:1,//1微信支付，2余额支付
        type:1,//1快递  2自提
        addressinfo: [],
        aid:0,//地址id
        shoparray:[],
        shopobjectArray: [],
        shopIndex:-1,
        shopId:0
    },
    bindPickerChange: function(e) {
        var that = this;
        this.setData({
          shopIndex: e.detail.value,
          shopId:that.data.shopobjectArray[e.detail.value]['id']
        })
    },
    //计算总价
    takeallmoney(){
        var that = this
        var allmoney=0;
        allmoney = parseFloat(that.data.shuliang * that.data.goodsinfo.price);
        //赋值
        that.setData({
            allmoney: allmoney.toFixed(2),
        });
        
    },
    stype:function(e){
        //配送方式
        var type = e.currentTarget.dataset.id;
        this.setData({
            type:type
        });
    },
    //重新选择收货地址
    changeaddress:function(){
        wx.navigateTo({
            url: '/pages/address/address?from=goumai',
        })
    },
    checkboxChange:function(e){
        if(this.data.paytype == 1){
            this.setData({
                paytype:2
            });
        }else{
            this.setData({
                paytype:1
            });
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        var userid=app.globalData.userId;
        var id = wx.getStorageSync('changeaddressid')||0;
        that.setData({
            aid: id,
        });
        //wx.removeStorageSync('changeaddressid');
        //请求数据并赋值
        util.httpRrquest(app.data.rooturl + 'user/getDefaultAddress', 'GET', { id: id,userid:userid })
        .then(function (response) {
            that.setData({
                aid: response.data.data.id,
                addressinfo: response.data.data
            });
        }, function (error) {
            console.log(error);
        });

        util.httpRrquest(app.data.rooturl + 'user/getDefaultZiti', 'GET', { userid: userid })
        .then(function (response) {
            if(response.data.data != null){
                that.setData({
                    name: response.data.data.pickName,
                    phone: response.data.data.pickPhone
                });
            }
            
        }, function (error) {
            console.log(error);
        });

        
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        
		var userid=app.globalData.userId;
        if(userid==''||userid==undefined||userid==null){
            
            return;
        }
        var that = this
        that.setData({
            id: options.id,
            ggid:options.ggid,
            shuliang:options.num?options.num:1,
            userinfo:app.globalData.userinfo
        });
        //获取订单设置信息
        this.orderset();
    },
    //输入框监听
    bindinput: function (e) {
        //console.log(e);
        var value = e.detail.value;
        var type = e.currentTarget.dataset.type;
        if (type.length > 0) {
            switch (type) {
                case 'name': //姓名
                    this.setData({
                        name: value,
                    })
                    break;
                case 'phone': //手机号码
                    this.setData({
                        phone: value,
                    })
                    break;
                case 'remark': //备注
                    this.setData({
                        remark: value,
                    })
                    break;
            }
        }
        //console.log(this.data);
    },
    orderset:function(){
        var that = this
        var userid=app.globalData.userId;
        //var userid=161;
        util.httpRrquest(app.data.rooturl + 'order/orderset', 'GET', { id:that.data.id,userid:userid,specId:that.data.ggid,buyType:1})
        .then(function (response) {
            var data = response.data.data;
            that.setData({
                goodsinfo: data.goodInfo

            });
            //计算总价
            that.takeallmoney();
        }, function (error) {
            console.log(error);
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        var shareinfo = app.setShareMessage();
        console.log(shareinfo);
        return {
            title: shareinfo.title,
            path: shareinfo.path,
            imageUrl: shareinfo.imageUrl,
            success: (res) => {
                wx.showToast({
                    title: "分享成功",
                    icon: 'loading'
                })
            }
        }
    },
    //数量加减
    count(idx){
        //如果是提货商品不允许修改数量
        
        let state=idx.currentTarget.dataset.index
        let num=this.data.shuliang
        if(state == 0){
            if(num==1){
                return
            }else{
                num-- 
            }
        }else{
            num++
        }
        this.setData({
            shuliang:num
        })
        this.takeallmoney();//计算总价
    },
    //下单
    order:function(){
        var that = this
        //订单信息
        if (that.data.id <-1 || that.data.shuliang <= 0 || that.data.allmoney <= 0) {
            wx.showToast({
                title: '请完善订单信息',
                icon: 'none'
            })
            return
        }
        if(that.data.type==1){
            if(that.data.aid==0){
                wx.showToast({
                    title: '请完善订单地址',
                    icon: 'none'
                })
                return
            }
        }
        if(that.data.type==2){
            if(that.data.name == undefined || that.data.name == '' || that.data.name == null){
                wx.showToast({
                    title: '请填写自提姓名',
                    icon: 'none'
                })
                return;
            }
            if(that.data.phone == undefined || that.data.phone == '' || that.data.phone == null){
                wx.showToast({
                    title: '请填写自提电话',
                    icon: 'none'
                })
                return;
            }

            if(that.data.shopId == undefined || that.data.shopId == '' || that.data.shopId == null || that.data.shopId == 0){
                wx.showToast({
                    title: '请选择店铺',
                    icon: 'none'
                })
                return;
            }
        }
        
        var str='';
        var allmoney = that.data.allmoney;
        var paytype = that.data.paytype;
        if(paytype == 1){
            if(allmoney>0){
                var str=str+'微信支付：'+allmoney;
            }
        }else{
            if(allmoney>0){
                var userBalance = app.globalData.userinfo.userBalance;
                console.log(userBalance,allmoney);
                if(parseFloat(userBalance)<parseFloat(allmoney)){
                    wx.showToast({
                        title: '余额不足',
                        icon: 'none'
                    })
                    return
                }
                var str=str+'余额支付：'+allmoney;
            }
        }
        
        var paramData={
            userid:app.globalData.userId,
            name: that.data.name,
            phone: that.data.phone,
            id: that.data.id,
            ggid:that.data.ggid,
            num: that.data.shuliang,
            remark: that.data.remark,
            allmoney:that.data.allmoney,
            paytype:paytype,
            aid: that.data.aid,
            logType:that.data.type,
            shopId:that.data.shopId
        };
        if(that.data.type == 3){
            util.httpRrquest(app.data.rooturl + 'order/addOrder', 'POST', paramData)
            .then(function (response) {
                var ordernum = response.data.data;
                util.httpRrquest(app.data.rooturl + 'order/success', 'GET', { onumber: ordernum})
                .then(function (response) {
                    //支付成功跳转
                    wx.redirectTo({
                        url: '/pages/order/order?state=0',
                    })
                })
            }, function (error) {
                console.log(error);
            });
        }else{
            wx.showModal({
                title: '提示',
                content: str,
                success (res) {
                    if (res.confirm) {
                        util.httpRrquest(app.data.rooturl + 'order/addOrder', 'POST', paramData)
                        .then(function (response) {
                            if(paytype == 1){
                                that.buys(response.data.data);
                            }else{
                                that.dbuys(response.data.data);
                            }
                        }, function (error) {
                            console.log(error);
                        });
                    }
                }
            })
        }
    },
    //下单处理支付
    buys: function (ordernum){
        var that=this;
        var userid=app.globalData.userId;
        util.httpRrquest(app.data.rooturl + 'order/weixinPay', 'GET', { onumber: ordernum,userid:userid})
            .then(function (response) {
                var data = response.data.data;
                var data = JSON.parse(data);
                wx.requestPayment({
                    timeStamp: data.timeStamp,
                    nonceStr: data.nonceStr,
                    package: data.package,
                    signType: data.signType,
                    paySign: data.paySign,
                    success(res) { 
                        //支付成功通知修改订单信息
                        util.httpRrquest(app.data.rooturl + 'order/success', 'GET', { onumber: ordernum})
                        .then(function (response) {
                            //支付成功跳转
                            wx.redirectTo({
                                url: '/pages/order/order?state=0',
                            })
                        })
                    },
                    fail(res) { 
                        //支付失败
                        wx.redirectTo({
                            url: '/pages/order/order?state=0',
                        })
                    }
                })
            },function (error) {
                console.log(error);
            });
    },
    //下余额支付单处理支付
    dbuys: function (ordernum){
        var that=this;
        var userid=app.globalData.userId;
        //支付成功通知修改订单信息
        util.httpRrquest(app.data.rooturl + 'order/success', 'GET', { onumber: ordernum})
        .then(function (response) {
            //支付成功跳转
            wx.redirectTo({
                url: '/pages/order/order?state=0',
            })
        })
    },
})